(function ($) {
    var defaults = {
            type: "get",
            data: {}
        },
        initTemplate = [
            '<div class="cjw_pager">',
            '<a class="prev"><i class="fa fa-angle-left"></i>上一页</a>',
            '<div class="page-list">',
            '<a data-num="1">1</a>',
            '</div>',
            '<a class="next">下一页<i class="fa fa-angle-right"></i></a>',
            '<a class="refresh"><i class="fa fa-refresh"></i></a>',
            '<a class="colSet"><i class="fa fa-cog"></i></a>',
            '<div class="set"><div></div></div>',
            '<span class="page-sum">共<strong class="allPage"></strong>页</span>',
            '<span class="page-go">跳转到<input class="inputPager" type="text">页</span>',
            '<a class="page-btn">GO</a>',
            '</div>'
        ].join(''),
        spanTemplate = '<span class="pagination-break">...</span>',
        $body = $(document.body);

    function getSetupHtml(cols, set) {
        var setupList = [];
        for (var i = 0, len = cols.length; i < len; i++) {
            setupList.push("<tr><td><input data-num=" + i + " type='checkbox' checked=" + ((set && set[i]) || true) + "/>" + cols[i] + "</td></tr>");
        }
        setupList.push("<tr><td><button class='btn'>确定</button><button class='btn'>取消</button></td></tr>");
        return "<table class='table-bordered'>" + setupList.join('') + "</table>";
    };

    function canel(that) {
        that.shade.detach();
        that.setup.hide();
    };

    var pager = function pager(opts) {
        return new pager.prototype.init(opts);
    };
    pager.prototype = {
        constructor: pager,
        nowPage: 1,
        selectFalse: [],
        isRefresh: false,
        init: function (options) {
            var that = this,
                opts = $.extend({}, defaults, options);
            that.options = opts;
            that.template = opts.template;
            opts.container.html(that.content = $(initTemplate));
            that.load();
            that.shade = $("<div class='shade'></div>");
            that.$input = that.content.find("input");
            that.content.find(".prev").on("click", function () {
                //上一页
                if (that.nowPage > 1) {
                    that.load(that.nowPage - 1);
                }
            }).next().on("click", "a", function () {
                that.load(parseInt($(this).attr("data-num")));
            }).next().on("click", function () {
                //下一页
                if (that.nowPage < that.total) {
                    that.load(that.nowPage + 1);
                }
            }).next().on("click", function () {
                that.load();
            }).next().on("click", function () {
                //列设置
                $body.after(that.shade);
                if (that.setup) {
                    that.setup.show();
                } else {
                    that.shade.on('click', function () {
                        canel(that);
                    })
                    $(this).next().children().html(that.setup = $(getSetupHtml(opts.cols)));
                    that.setup.find("button").eq(0).on("click", function () {
                        var falseList = [];
                        that.setup.find("input[type=checkbox]").each(function () {
                            var $this = $(this);
                            if (!$this.prop("checked")) {
                                var num = $this.attr("data-num");
                                if (num) {
                                    falseList.push(num);
                                }
                            }
                        })
                        if (that.selectFalse.toString() != falseList.toString()) {
                            that.selectFalse = falseList;
                            that.isRefresh = true;
                        }
                        that.load();
                        canel(that);
                    }).end().eq(1).on("click", function () {
                        canel(that);
                    })
                }
            }).nextAll(".page-btn").on("click", function () {
                var num = parseInt(that.$input.val());
                if (!isNaN(num)) {
                    that.load(num);
                }
            });
        },
        load: function (num) {
            var that = this,
                opts = that.options;
            num = num || that.nowPage;
            opts.data.end = num * 10;
            opts.data.start = opts.data.end - 9;
            that.nowPage2 = num;
            if (opts.url) {
                var opt = {
                    url: opts.url,
                    type: opts.type,
                    data: opts.data,
                    success: function (result) {
                        that.render(result);
                    }
                }
                $.ajax(opt);
            }
        },
        render: function (result) {
            var that = this,
                content = that.content,
                nowPage = that.nowPage,
                pagesum = result.pagesum;
            that.$input.val("");
            if (that.total != pagesum) {
                content.find(".allPage").html(pagesum);
                that.total = pagesum;
            }
            if (nowPage != that.nowPage2) {
                that.nowPage = nowPage = that.nowPage2;
            }
            var pagelist = [];
            pagelist.push("<a data-num='1'>1</a>");
            var i;
            if (nowPage < 4) {
                i = 2;
            } else if (nowPage > pagesum - 3) {
                i = pagesum - 3;
            }
            else {
                i = nowPage - 1;
            }
            for (var len = i + 3; i < len; i++) {
                pagelist.push("<a data-num='" + i + "'>" + i + "</a>");
            }
            if (i != pagesum) {
                pagelist.splice(4, 0, spanTemplate);
            }
            if (i != 5) {
                pagelist.splice(1, 0, spanTemplate);
            }
            pagelist.push("<a data-num='" + pagesum + "'>" + pagesum + "</a>");
            content.find(".page-list").html($(pagelist.join(''))).find("[data-num=" + nowPage + "]").addClass("current");
            if (that.options.table) {
                that.renderTable(result);
            }
            that.options.render(result);
        },
        renderTable: function (result) {
            var that = this,
                selectFalse = that.selectFalse,
                opts = that.options;
            if (!that.cols) {
                that.getCols();
                opts.table.children("thead").html(that.cols);
            }
            if (that.isRefresh) {
                that.getCols();
                var $template = $(opts.template),
                    $td = $template.children(),
                    $td2 = that.cols.children();
                for (var i = selectFalse.length - 1; i > -1; i--) {
                    $td.eq(selectFalse[i]).remove();
                    $td2.eq(selectFalse[i]).remove();
                }
                that.template = $template;
                that.isRefresh = false;
                opts.table.children("thead").html(that.cols);
            }
            opts.table.children("tbody").html(cjw_common.transformTemplate(that.template, result.data));
        },
        getCols: function () {
            var that = this,
                colList = [],
                cols = that.options.cols;
            for (var i = 0, len = cols.length; i < len; i++) {
                colList.push("<th>" + cols[i] + "</th>");
            }
            that.cols = $("<tr>" + colList.join('') + "</tr>");
        }
    };
    pager.prototype.init.prototype = pager.prototype;
    $.pager = pager;
})(jQuery);